package util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.xml.transform.TransformerException;
import javax.xml.transform.stream.StreamSource;

import org.springframework.ws.WebServiceMessage;
import org.springframework.ws.client.core.WebServiceMessageCallback;
import org.springframework.ws.client.core.WebServiceMessageExtractor;
import org.springframework.ws.client.core.WebServiceTemplate;

public class EnhancedWebServiceTemplate extends WebServiceTemplate {
	
	public String sendStreamReceiveString(final InputStream request) {
		Object rs = sendAndReceive(
			new WebServiceMessageCallback() {
				@Override
				public void doWithMessage(WebServiceMessage message) throws IOException, TransformerException {
					createTransformer().transform(new StreamSource(request), message.getPayloadResult());
				}
			}, 
			new WebServiceMessageExtractor() {
				@Override
				public Object extractData(WebServiceMessage message) throws IOException, TransformerException {
					ByteArrayOutputStream bos = new ByteArrayOutputStream();
					message.writeTo(bos);
					return new String(bos.toByteArray());
				}
			}
		);
		
		return (String) rs;
	}
	
	@SuppressWarnings("unchecked")
	public <T> T marshalSendAndReceive(Object requestPayload, Class<T> reponseType) {
		return (T) marshalSendAndReceive(requestPayload);
	}
	
	
}
